/**
 *  奖励切水果关卡
 */
class AwardCustomsUI extends UIBase{
    // private mg: egret.Graphics;
    // private mg1: egret.Graphics;
    // private mPoints: any[];
    // private mPenSize: number = 4;
    private mPrev: number;
    private mIsDown: boolean;

    private mMS: number = 1000;
    private mStartTime:number;
    private mItems:fruit[] = [];
    private fruit_group:eui.Group;
    private timer:number;
    private count= 0;
    private lb_time:eui.Label;
    private isGameOver:boolean = false;
    private fruitCnt = 0;
    private img_light:eui.Image;
    private img_float_world:eui.Image;
    protected killNum:number = 0;
    protected totalNum = 0;
    // private boom:Boom;
    private mask_group:eui.Group;
    private touchId;
    private system:particle.ParticleSystem;
    private btn_sure:BaseButton;
    private group_state:eui.Group;
    private img_prepare:eui.Image;
    private btn_home:BaseButton;
    private isjump = false;

    private bombList = [];

    constructor()
    {
        super('AwardCustomsView',{showBG:true});
    }

    public init()
    {
        super.init(true);
        let sprite1: egret.Shape = new egret.Shape();
        let sprite: egret.Shape = new egret.Shape();
        this.addChild( sprite1 );
        this.addChild( sprite );

        // this.mg1 = sprite1.graphics;
        // this.mg = sprite.graphics;
        // this.mPoints = [];
        this.mask_group.visible = true;
        this.mPrev = 0;
        this.timer = 60;
        this.mStartTime = egret.getTimer();
        this.mMS = 1000;
        // this.boom.y = this.fruit_group.height + 200;
        let flag: number = Math.random() > 0.5 ? 1 : -1;
        // this.boom.x = this.fruit_group.width / 2 + flag * Math.random() * 100;
        // this.boom.y = this.fruit_group.height + 10;
        
        this.addParticle();
    }

    public addParticle()
    {
        let texture = RES.getRes('particle_18');
        let config = RES.getRes('particle_52_json');
        this.system = new particle.GravityParticleSystem(texture, config);
        this.fruit_group.addChildAt(this.system,0);
        this.system.emitterX = 0;
        this.system.emitterY = 0;
    }

    public cutAllFruit()
    {
        let list = this.mItems;
        for(let i in list)
        {
            let fruit = list[i] as fruit;
            let fruitData = fruit.Data;
            let data = {
                id:fruitData.id,
                color:fruitData.color
            }
            let item = fruitBoomItem.getBoomItem(data);
            if(!this.fruit_group.contains(item))
            this.fruit_group.addChildAt(item,1);
            item.x = fruit.x;
            item.y = fruit.y;
            item.boom(fruit.killed, fruit);
        }
        this.removeAllBomb();
        this.GameOver();
    }

    protected floatWorld()
    {
        if(this.killNum <= 2)return;
        let frame = 100/3;
        let source = '';
        let rand = Math.random();
        if(this.killNum > 4)
        {
            source = 'AMAZING';
            SoundManager.instance().playSound('amazing');
        }
        else if(this.killNum == 2)
        {
            source = 'GOOD';
            SoundManager.instance().playSound('good');
        }
        else if(this.killNum == 3){
            source = 'GREAT';
            SoundManager.instance().playSound('great');
        }
        else{
            source = 'EXCELLENT';
            SoundManager.instance().playSound('excellent');
        }
        
        this.img_float_world.source = source;
        this.img_float_world.anchorOffsetX = this.img_float_world.width >> 1;
        this.img_float_world.anchorOffsetY = this.img_float_world.height >> 1;
        this.img_float_world.x = this.img_light.x;
        this.img_float_world.y = this.img_light.y;
        egret.Tween.get(this.img_float_world).to({
            scaleX:2,
            scaleY:2
        }, 3 * frame).to({
            scaleX:1.5,
            scaleY:1.5
        }, 3 * frame).wait(24 * frame).set({
            scaleX:0,
            scaleY:0
        })
        // egret.Tween.get(this.img_light).to({
        //     scaleX:0.5,
        //     scaleY:0.5
        // }, 3 * frame).to({
        //     scaleX:0.3,
        //     scaleY:0.3
        // }, 3 * frame).wait(24 * frame).set({
        //     scaleX:0,
        //     scaleY:0
        // })
        this.killNum = 0;
    }

    public updateTime()
    {
        if(this.isGameOver)return;
        let time = this.timer;
        this.lb_time.text = `倒计时:${time}`;
        if(time <= 10)
        {
            this.lb_time.scaleX = this.lb_time.scaleY = 50;
        }
        egret.Tween.get(this.lb_time).to({
            scaleX:1,
            scaleY:1
        }, 300);
    }

    public addEvent()
    {
        this.btn_sure.addTapHandler(this.startGame, this);
        this.btn_home.addTapHandler(this.backHome, this);
        this.fruit_group.addEventListener( egret.TouchEvent.TOUCH_BEGIN,this.onTouchBeginHandler,this );
        this.fruit_group.addEventListener( egret.TouchEvent.TOUCH_MOVE,this.onTouchMoveHandler,this );
        this.fruit_group.addEventListener( egret.TouchEvent.TOUCH_END,this.onTouchEndHandler,this );
        // egret.startTick( this.onLoopHandler,this );
    }


    protected backHome()
    {
        this.isjump = true;
        ScreenMovies.MovieStart(2,()=>{
            let da = {
                index:0
            }
            UIManager.instance().openUILogic(MainUI, da);
        },this);
    }

    public startGame()
    {
        this.group_state.visible = false;
        SoundManager.instance().playSound('ready_go_mp3');
        egret.Tween.get(this.img_prepare).to({
            scaleX:1,
            scaleY:1,
            alpha:1
        }, 600).wait(400).set({
            source:'img_go_png'
        }).to({
            alpha:0,
            scaleX:0,
            scaleY:0
        }, 700, egret.Ease.backIn).call(this.gameStart, this);
    }

    public gameStart()
    {
        this.mask_group.visible = false;
        egret.startTick( this.onLoopHandler,this );
    }

    // public addBoom()
    // {
    //     if(!this.boom.visible)
    //     {
    //         let rand = Math.random();
    //         if(rand < 0.3)return;
    //         this.boom.born_1();
    //         if(this.boom.x < 0 || this.boom.x > this.width + 50)
    //         {
    //             let flag: number = Math.random() > 0.5 ? 1 : -1;
    //             this.boom.x = this.fruit_group.width / 2 + flag * Math.random() * 100;
    //         }
            
    //         // this.boom.y = this.fruit_group.height + 150;
    //     }
    // }

    protected addBomb()
    {
        let bomb = Boom.getBomb();
        if(!this.fruit_group.contains(bomb))
        this.fruit_group.addChildAt( bomb ,10);
        let flag: number = Math.random() > 0.5 ? 1 : -1;
        bomb.x = this.fruit_group.width / 2 + flag * Math.random() * 100;
        bomb.y = this.fruit_group.height + 10;
        bomb.born_1();
        this.bombList.push(bomb)
    }

    private onLoopHandler(t:number):boolean
	{
        // this.onRunHandler();
        if(!this.mItems)return;
        this.count++;
        if(this.count % 60 == 0)
        {
            this.timer--;
            this.count = 0;
            this.updateTime();
            this.floatWorld();
            if(this.timer < 50)
            {
                this.addBomb();
            }
        }
        // if(this.timer < 50)
        // {
        //     this.addBoom();
        // }
        if(this.timer <= 0 && !this.isGameOver)
        {
            this.GameOver();
        }
        if(this.timer == 50)
        {
            this.mMS = 300;
        }
        else if(this.timer == 30)
        {
            this.mMS = 200;
        }
        else if(this.timer == 5)
        {
            this.mMS = 100;
        }
        else if(this.timer == 40 || this.timer == 20)
        {
            this.mMS = 500;
        }
        let cutTime = egret.getTimer();
        if(cutTime - this.mStartTime >= this.mMS)
        {
            this.createItems();
            this.mStartTime = cutTime;
        }
        let _count: number = this.mItems.length;
        if( _count ){
            for( let i: number = 0;i < _count;i ++){
                let fruit: fruit = this.mItems[i];
                fruit.action();
                if( fruit.y > this.fruit_group.height + 20 ){
                    this.mItems.splice( i,1 );
                    FruitPool.pushFruit(fruit);
                    _count = this.mItems.length;
                    i--;
                }
            }
        }
        this.updateBomb();
        // if(this.boom.visible)
        // {
        //     this.boom.action_1();
        //     if(this.boom.y > this.fruit_group.height + 20)
        //     {
        //         this.boom.visible = false;
        //     }
        // }
        return false;
	}

    public updateBomb()
    {
        let list = this.bombList;
        for(let v of list)
        {
            v.action_1();
            if(v.y >= this.fruit_group.height + 20)
            {
                let index = list.indexOf(v);
                list.splice(index, 1);
                v.reset();
                continue;
            }
        }
    }

    public GameOver()
    {
        this.mMS = 1000;
        this.isGameOver = true;
        let data = {
            fruit_num:this.totalNum
        }
        AccountPrase.instance().special_account(data);
    }

    public getFruit(id)
    {
        let data = DataJson.fruit_data[id];
        let fruit = FruitPool.getFruit(data);
        return fruit;
    }

    public removeAllBomb()
    {
        for(let v of this.bombList)
        {
            v.remove();
        }
        this.bombList = [];
        Boom.clearPool();
    }

    private createItems()
    {
        let fruitNum = GameConst.furitNum;
        let fruit_id = Math.floor(Math.random()* fruitNum + 1);
        let fruit: fruit = this.getFruit(fruit_id);
        if(!this.fruit_group.contains(fruit))
        this.fruit_group.addChildAt( fruit ,0);

        let rand: number = Math.floor( Math.random() * 3 );
        fruit.born();
        let flag: number = Math.random() > 0.5 ? 1 : -1;
        fruit.x = this.width / 2 + flag * Math.random() * 250;
        fruit.y = this.fruit_group.height + 30;
        this.mItems.push( fruit );
    }

    private onTouchBeginHandler( e:egret.TouchEvent):void
    {
        this.touchId = e.touchPointID;
        this.mIsDown = true;
        // let obj = { sx: e.localX,sy: e.localY,size: this.mPenSize,size1: this.mPenSize + 10};
        // this.mPoints.push( obj );
        let _x: number = e.stageX;
        let _y: number = e.stageY;
        if(this.system)
        {
            this.system.start();
            this.system.visible = true;
            this.system.emitterX = _x;
            this.system.emitterY = _y;
        }
    }

    protected checkHitBoom(_x, _y)
    {
        let localPoint = this.fruit_group.globalToLocal(_x, _y);
        let len = this.bombList.length;
        for(let i=0;i<len;i++)
        {
            let boom = this.bombList[i];
            if(( localPoint.x > (boom.x - boom.width / 2) ) && ( localPoint.x < (boom.x + boom.width / 2) )
            && ( localPoint.y > (boom.y - boom.height / 2) ) && ( localPoint.y < (boom.y + boom.height / 2) ))
            {
                this.removeBombExitSelf(boom);
                this.removeEvent();
                // this.mg.clear();
                // this.mg1.clear();
                this.system.stop();
                this.system.visible = false;
                this.isGameOver = true;
                boom.boom();
                SoundManager.instance().stop();
                SoundManager.instance().playSound('bomb_mp3',1);
                break;
            } 
        }
    }

    private onTouchMoveHandler( e:egret.TouchEvent):void
    {
        if(this.touchId != e.touchPointID)
        {
           return;
        }
        if( this.mIsDown && !this.isGameOver){
            // let pt = { sx: e.stageX,sy: e.stageY,size: this.mPenSize,size1: this.mPenSize + 10 };
            // this.mPoints.push( pt );
            let _x: number = e.stageX;
            let _y: number = e.stageY;
            if(this.system.visible)
            {
                this.system.emitterX = _x;
                this.system.emitterY = _y;
            }
            let _count: number = this.mItems.length;
            this.checkHitBoom(_x,_y);
            for( let i = 0;i < _count;i++){
                let fruit: fruit = this.mItems[i];
                if(( _x > (fruit.x - fruit.width / 2) ) && ( _x < (fruit.x + fruit.width / 2) )
                    && ( _y > (fruit.y - fruit.height / 2) ) && ( _y < (fruit.y + fruit.height / 2) )){//可以切

                    this.killNum ++;
                    this.totalNum ++;
                    let fruitData = fruit.Data;
                    let data = {
                        id:fruitData.id,
                        color:fruitData.color
                    }

                    this.mItems.splice( i,1 );
                    _count = this.mItems.length;
                    i--;
                    this.fruitCnt++;

                    //添加爆炸效果
                    let item = fruitBoomItem.getBoomItem(data);
                    if(!this.fruit_group.contains(item))
                    this.fruit_group.addChildAt(item,1);
                    item.x = fruit.x;
                    item.y = fruit.y;
                    item.boom(fruit.killed, fruit);
                    WeChatgGameManager.instance().vibrateShort();
                }
            }
        }
    }

    private onTouchEndHandler( e:egret.TouchEvent):void
    {
        if(this.touchId != e.touchPointID)
        return;
        this.mIsDown = false;
        let _x: number = e.stageX;
        let _y: number = e.stageY;
        if(this.system)
        {
            this.system.stop();
            // this.system.visible = false;
            this.system.emitterX = _x;
            this.system.emitterY = _y;
        }
    }

    private onRunHandler( ): void {
        // if(!this.mPoints ||  this.mPoints.length == 0 ) return;
        // this.mg.clear();
        // this.mg1.clear();
        // let _count: number = this.mPoints.length;
        // for(let i: number = 0;i < _count;i++ ) {
        //     let pt = this.mPoints[i];
        //     pt.size -= 0.3;
        //     pt.size1 -= 1;
        //     if( pt.size < 0 ) {
        //         this.mPoints.splice( i,1 );
        //         i--;
        //         _count = this.mPoints.length;
        //     }
        // }
        // _count = this.mPoints.length;
        // for(let i = 1;i < _count;i++ ) {
        //     let p = this.mPoints[i];
        //     this.mg.lineStyle( p.size,0x1BB6BA );
        //     this.mg.moveTo( this.mPoints[i - 1].sx,this.mPoints[i - 1].sy );
        //     this.mg.lineTo( p.sx,p.sy );
        //     this.mg1.lineStyle( p.size1,0x63FF0F );
        //     this.mg1.moveTo( this.mPoints[i - 1].sx,this.mPoints[i - 1].sy );
        //     this.mg1.lineTo( p.sx,p.sy );
        // }
    }

    //移除除了本身之外的炸弹
    public removeBombExitSelf(bomb)
    {
        for(let v of this.bombList)
        {
            if(bomb != v)
            {
                v.remove();
                let index = this.bombList.indexOf(v);
                this.bombList.splice(v, 1);
            }
        }
    }

    public removeEvent()
    {
        egret.stopTick( this.onLoopHandler,this );
        this.btn_sure.removeTapHandler();
        this.fruit_group.removeEventListener( egret.TouchEvent.TOUCH_BEGIN,this.onTouchBeginHandler,this );
        this.fruit_group.removeEventListener( egret.TouchEvent.TOUCH_MOVE,this.onTouchMoveHandler,this );
        this.fruit_group.removeEventListener( egret.TouchEvent.TOUCH_END,this.onTouchEndHandler,this );
    }

    public clear()
    {
        SoundManager.instance().goOn();
        super.clear();
        this.removeAllBomb();
        this.isGameOver = null;
        for(let v of this.mItems)
        {
            v.remove();
        }
        this.mItems = null;
        this.fruit_group.removeChildren();
        // this.mg = null;
        // this.mg1 = null;
        // this.mPoints = null;
        // this.mPenSize = null;
        this.mIsDown = null;

        this.mMS = null;
        this.mStartTime = null;
        this.timer = null;
        this.count = null;
        this.fruitCnt = null;
        this.killNum = null;

        if(this.system)
        {
            this.system.stop();
            this.system = null;
        }

        FruitPool.clearPool();
        fruitBoomItem.clearPool();
        if(!this.isjump)
        UIManager.instance().openUILogic(GameUI);
        this.isjump = null;
    }
}